<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://cdn.bootcdn.net/ajax/libs/iview/3.5.5-rc.1/styles/iview.min.css" rel="stylesheet">
<link rel="stylesheet" href="__CBTCSS__/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<style>
.section {
  background-color: #fff;
  height: 56px;
  margin: 0px;
  padding: 12px;
}
</style>
<title>文章创作 - MZBlog</title>
</head>

<body class="bg-light">
<div id="app">

<section class="section">
  <Row :gutter="8">
    <i-col :xs="3" :sm="4" :md="4" :lg="3" :xl="2">
      <i-button type="primary" ghost icon="ios-arrow-back" style="width:100%;" @click="toArticleList">
        <span v-if="screenWidth > 575">文章列表</span>
      </i-button>
    </i-col>
    <i-col :xs="17" :sm="10" :md="12" :lg="12" :xl="10">
      <i-input v-model.trim="postForm.title" :maxlength="100" show-word-limit placeholder="请输入100个字以内的文章标题" style="width:100%;" />
    </i-col>
    <i-col :xs="6" :sm="6" :md="5" :lg="4" :xl="3" v-if="screenWidth > 575">
1
    </i-col>
    <i-col :xs="4" :sm="4" :md="3" :lg="5" :xl="{ span: 3, offset: 6 }">
      <i-button type="success" style="min-width:100%;" @click="onSubmit">保存</i-button>
    </i-col>
  </Row>
</section>

<div class="container-fluid">
  <div class="row d-block">
    <textarea id="editor"></textarea>
  </div>
</div>

</div>
</body>
</html>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/iview/3.5.5-rc.1/iview.min.js"></script>
<script src="__CBTCSS__/jquery/3.4.1/jquery.min.js"></script>
<script src="__BTBLOG__/ckeditor5/ckeditor.js"></script>
<script src="__BTBLOG__/ckeditor5/translations/zh-cn.js"></script>

<script>
var app = new Vue({
  el: '#app',
  data() {
    return {
      // 指定编辑的资源ID 0.新增 其他.指定的资源ID
      editId: 0,
      // 页面级加载等待
      loading: false,
      // 文章数据
      postForm: {
        title: '',
        content: '',
        content_html: '',
        code_style: 'monokai-sublime', // markdown样式
        editor_type: 'ckeditor',
        status: 5,
      },

      // ######################################################################################################################

      // 编辑器高度
      editorHeight: document.body.clientHeight - 56,
      // 屏幕宽度
      screenWidth: document.body.clientWidth,

      // ######################################################################################################################

      // 编辑器实例
      editor: null,

    }
  },
  watch:{
    screenWidth(val){
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if(!this.timer){
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        setTimeout(() => {
          this.timer = false
        },400)
      }
    }
  },
  mounted() {
    window.onresize = () => {
      return this.screenWidth = document.body.clientWidth
    }
    this.initCKEditor()
    this.editId = this.getQueryVariable('id') ? parseInt(this.getQueryVariable('id')) : 0
    if(this.editId) {
      this.getFormData()
    }
  },
  methods: {
    // ######################################################################################################################
    // # 编辑器操作方法
    // ######################################################################################################################

    // 初始化编辑器
    initCKEditor () {
      ClassicEditor.create( document.querySelector( '#editor' ), {
        // removePlugins: [ 'Heading', 'Link' ],
        // toolbar: [ 'bold', 'italic', 'bulletedList', 'numberedList', 'blockQuote' ],
        heading: {
          options: [
            { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
            { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
            { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' }
          ]
        },
        language : 'zh-cn',
        ckfinder: {
          uploadUrl: '/article/ckeditor5/upload',
        },
      })
      .then(editor => {
        this.editor = editor;
      })
      .catch( error => {
        console.error( error );
      });
    },

    // 获取编辑器内容
    getContentHtml() {
      this.postForm.content = this.editor.getData()
    },

    // ######################################################################################################################
    // # 写博客 MarkDown编辑器 保存和编辑 操作方法
    // ######################################################################################################################

    // 读取指定的资源用于编辑
    getFormData () {
      this.loading = true
      editContent(this.editId).then(async res => {
        if (res.status === 200) {
          this.postForm = res.data
        } else {
          this.$Notice.error( {title: res.msg} )
        }
        this.loading = false
      }).catch(res => {
        this.loading = false
        this.$Notice.error( {title: res.msg} )
      })
    },
    // 提交表单
    onSubmit() {
      if(this.postForm.title == '') {
        this.$Message.warning('文章标题不能为空')
        return
      }
      this.getContentHtml()
      if(this.editId) {
        this.handleUpdate(true)
      } else {
        this.handleStore()
      }
    },
    // 保存新建的资源
    handleStore() {
      this.loading = true
      this.getContentHtml()
      storeContent(this.postForm).then(async res => {
        if (res.status === 200) {
          this.$Notice.success({title: '保存成功'})
          this.$router.push({ path: '/new/markdown/'+res.data.akey })
        } else {
          this.$Message.error(res.msg);
        }
        this.loading = false
      }).catch(res => {
        this.$Message.error(res.msg);
        this.loading = false
      })
    },
    // 保存更新的资源 
    handleUpdate(val = false) {
      if(this.editId) {
        this.getContentHtml()
        updateContent(this.editId, this.postForm).then(async res => {
          if (res.status === 200) {
            val ? this.$Notice.success({title: '保存成功'}) : this.$Message.success('保存成功')
          } else {
            this.$Message.error(res.msg);
          }
          this.loading = false
        }).catch(res => {
          this.$Message.error(res.msg);
          this.loading = false
        })
      }
    },

    // ######################################################################################################################
    // # 
    // ######################################################################################################################

    // 跳转到文章列表页
    toArticleList() {
        this.$router.push({ path: '/admin/article/list' })
    },

    // 获取URL参数
    getQueryVariable(variable) {
      var query = window.location.search.substring(1)
      var vars = query.split("&")
      for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=")
        if(pair[0] == variable){ return pair[1] }
      }
      return false
    },

  }
})
</script>